package com.cloudbroker.bcs.common.emoji;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.IOUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuyn15828 on 2016/4/26.
 */
public class EmojiLoader {
    private EmojiLoader() {
    }

    public static List<Emoji> loadEmojis(InputStream stream) throws IOException {
        JSONArray emojisJSON = JSONArray.parseArray(new String(IOUtil.streamToBytes(stream) , "UTF-8"));
        ArrayList emojis = new ArrayList(emojisJSON.size());

        for(int i = 0; i < emojisJSON.size(); ++i) {
            Emoji emoji = buildEmojiFromJSON(emojisJSON.getJSONObject(i));
            if(emoji != null) {
                emojis.add(emoji);
            }
        }

        return emojis;
    }

    private static String inputStreamToString(InputStream stream) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));

        String read;
        while((read = br.readLine()) != null) {
            sb.append(read);
        }

        br.close();
        return sb.toString();
    }

    protected static Emoji buildEmojiFromJSON(JSONObject json) throws UnsupportedEncodingException {
        if(!json.containsKey("emoji")) {
            return null;
        } else {
            byte[] bytes = json.getString("emoji").getBytes("UTF-8");
            String description = null;
            if(json.containsKey("description")) {
                description = json.getString("description");
            }

            boolean supportsFitzpatrick = false;
            if(json.containsKey("supports_fitzpatrick")) {
                supportsFitzpatrick = json.getBoolean("supports_fitzpatrick");
            }

            List aliases = jsonArrayToStringList(json.getJSONArray("aliases"));
            List tags = jsonArrayToStringList(json.getJSONArray("tags"));
            return new Emoji(description, supportsFitzpatrick, aliases, tags, bytes);
        }
    }

    private static List<String> jsonArrayToStringList(JSONArray array) {
        ArrayList strings = new ArrayList(array.size());

        for(int i = 0; i < array.size(); ++i) {
            strings.add(array.getString(i));
        }

        return strings;
    }
}
